package de.slothsoft.bookmaker.parse.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;

import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.DomSerializer;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.w3c.dom.Document;
import org.w3c.dom.xpath.XPathException;

import de.slothsoft.bookmaker.parse.ImageXPathParser;
import de.slothsoft.bookmaker.parse.ParseContext;
import de.slothsoft.bookmaker.parse.WebsiteDescription;
import de.slothsoft.bookmaker.parse.WebsiteParser;
import de.slothsoft.bookmaker.parse.XPathUtil;

public class MangaEdenDescription implements WebsiteDescription {

    public static final String REGEX_URL = "http(s){0,1}://(www.){0,1}mangaeden.com/(.*)";

    @Override
    public String getDisplayName() {
        return "mangaeden.com";
    }

    @Override
    public boolean isSupported(String url) {
        return url.matches(REGEX_URL) && url.endsWith("/1/");
    }

    @Override
    public WebsiteParser createParser(ParseContext context, InputStream input) throws IOException {
        ImageXPathParser parser = createParser(input, context.getUrl());
        context.getProgressMonitor().setStep(0.5 / parser.getPageUrls().size());
        return parser;
    }

    protected static ImageXPathParser createParser(InputStream input, final String inputUrl) throws IOException {
        try {
            TagNode tagNode = new HtmlCleaner().clean(input);
            Document document = new DomSerializer(new CleanerProperties()).createDOM(tagNode);
            List<String> pageUrls = XPathUtil.findAttributes(document, "//a[@class='ui-state-default']", "href");
            cleanUpPageUrls(pageUrls, inputUrl);
            String title = XPathUtil.findAttribute(document, "/html/head/meta[@name='description']", "content");
            if (title != null) {
                title = title.replace("MangaEden Avatar: ", "").replaceAll(":[^:]*", "");
            }
            return ImageXPathParser.createForMangaEden(title, pageUrls);
        } catch (XPathException | ParserConfigurationException | XPathExpressionException e) {
            throw new IOException(e);
        }
    }

    private static void cleanUpPageUrls(List<String> pageUrls, final String inputUrl) {
        // missing: [matches(text(),'[0-9]+']
        pageUrls.remove(0); // javascript: void(0);
        pageUrls.remove(0); // /mymanga/
        pageUrls.remove(0); // previous page
        int length = pageUrls.size();
        for (int i = 0; i < length; i++) {
            pageUrls.set(i, "http://www.mangaeden.com" + pageUrls.get(i));
        }
        if (inputUrl != null) {
            pageUrls.add(0, inputUrl);
        }
    }

}
